package com.imachen.ymcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.imachen.ymcc.domain.PayOrder;
import com.imachen.ymcc.dto.PayDto;
import com.imachen.ymcc.enums.GlobalExceptionCode;
import com.imachen.ymcc.service.IPayOrderService;
import com.imachen.ymcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @description: 课程订单支付消费者
 * @author: AChen
 * @date: 2022/10/17 0017 : 18:43
 * @version: ver1.0
 * @email
 */
@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "course-order-pay-consumer",
        topic = "tx-course-order-topic",
        selectorExpression = "tx-course-order-tag"
)
public class CourseOrderPayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    /**
     *  消费者有一个签收模式：
     *      什么都不返回：签收成功
     *      报错了：签收失败，重新发送
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        // 获取消息参数，业务校验
        byte[] body = messageExt.getBody();
        String pram = new String(body, StandardCharsets.UTF_8);
        PayDto payDto = JSON.parseObject(pram, PayDto.class);
        AssertUtil.isNotNull(payDto, GlobalExceptionCode.ERROR);
        // 获取支付单
        PayOrder payOrder = payOrderService.selectPayByOrderNo(payDto.getOrderNo());
        if (payOrder != null) {
            // 如果支付单存在，那么说明之前已经生成支付单了但是可能没有签收成功，那么直接return空，代表签收
            return;
        }

        // 保存支付单信息
        payOrder = new PayOrder();
        payOrder.setCreateTime(new Date());
        payOrder.setAmount(payDto.getTotalAmount());
        payOrder.setPayType(payDto.getPayType());
        payOrder.setOrderNo(payDto.getOrderNo());
        payOrder.setUserId(payDto.getUserId());
        payOrder.setSubject(payDto.getTitle());
        payOrder.setPayStatus(PayOrder.WAIT_PAY_STATUS);
        payOrder.setExtParams(payDto.getExtParams());
        payOrderService.insert(payOrder);
    }
}
